package concurrent;

import entity.Student;
import org.junit.Test;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author zhangxin
 * @date 2021/3/23
 */
public class CASTest {

    @Test
    public void t(){
        Integer a = 0;
        int b = 0;
        for (int i = 0; i < 99; i++) {
            a = a ++;
            b = a ++;
        }

        System.out.println(a);
        System.out.println(b);
    }

    public static void main(String[] args) {
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);

            Unsafe unsafe = (Unsafe)theUnsafe.get(null);

            Student student = new Student();
            student.setAge(23);

            System.out.println("before cas" + student);

            long ageOffset = unsafe.objectFieldOffset(Student.class.getDeclaredField("age"));
            unsafe.compareAndSwapInt(student, ageOffset, 23, 712);

            System.out.println("after cas" + student);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}
